<script setup>
import {ref, reactive, computed, watch} from 'vue'
import {getKnowledgeCategories, httpKnowledgeList, updateUseTimes} from '@/api/knowledge.js'
import Pagination from '@/components/pagination/index.vue'
import useCollectStore from '@/stores/collect.js'
import useKnowledgeStore from '@/stores/knowledge.js'
const collectStore = useCollectStore()
const knowledgeStore = useKnowledgeStore()
const loading = ref(false)
const allCategories = ref([])
const knowledgeList = ref([])
const knowledgeTotal = ref(0)
const imagePrefix = import.meta.env.VITE_IMAGE_SUFFIX
import FireFilled from '@/icons/FireFilled.vue'
const query = reactive({
  sort_id: 0,
  page: 1,
  keyword: '',
  limit: 20,
  is_private: 0,
})

const props = defineProps({
  isPrivate: Number,
  selectKnowledge: Function,
  show: Boolean,
  hideDialog: Function
})

watch(() => props.isPrivate, (newValue) => {
  query.is_private = newValue
  init()
})

const useKnowledge = (item) => {
  if (knowledgeStore.getKnowledge().id === item.id) {
    return
  }
  knowledgeStore.setKnowledge(item.id, item.name)
  updateUseTimes(item.id).catch(() => {})
  props.selectKnowledge({id: item.id, name: item.name})
}

const allAvatars = computed(() => {
  return knowledgeList.value.map(item => {
    return imagePrefix + item.avatar
  })
})

const init = async () => {
  loading.value = true
  await getCategories(false)
  await collectStore.getKnowledgeCollects()
  await getList(false)
  loading.value = false
}

const getCategories = async (showLoading = true) => {
  if (showLoading) loading.value = true
  const response = await getKnowledgeCategories().catch(() => null)
  if (showLoading) loading.value = false
  if (!response) return
  let {list} = response
  list = [
    {
      id: 0,
      sort_name: '全部'
    },
    {
      id: -1,
      sort_name: '我的收藏'
    }
  ].concat(list)
  allCategories.value = list.map(item => {
    return {
      id: item.id,
      name: item.sort_name
    }
  })
}

const changeCategory = () => {
  query.page = 1
  getList()
}

const getList = async (showLoading = true) => {
  if (showLoading) loading.value = true
  const response = await httpKnowledgeList({...query}).catch(() => null)
  if (showLoading) loading.value = false
  if (!response) return
  const {list, total} = response
  knowledgeList.value = list
  knowledgeTotal.value = total
}

</script>

<template>
  <el-dialog
       :model-value="show"
       :close-on-click-modal="false"
       append-to-body
       top="20px"
       width="1100px"
       draggable
       :title="`选择${isPrivate ? '资料库' : '知识库'}`"
       center
       @close="hideDialog"
  >
    <div class="pw-100 knowledge-bg knowledge-base">
      <el-tabs v-model="query.sort_id" @tab-change="changeCategory" v-if="isPrivate === 0">
        <el-tab-pane
            v-for="(item) in allCategories"
            :label="item.name"
            :name="item.id"
        ></el-tab-pane>
      </el-tabs>
      <div>
        <el-input
            prefix-icon="Search"
            v-model="query.keyword"
            @keyup.native.enter="changeCategory"
            maxlength="32"
            clearable
            placeholder="搜索知识库"
            class="w-300 margin-left-10"
        />
        <el-button class="margin-left-10" icon="Search" type="primary" @click="changeCategory">搜索</el-button>
      </div>
      <div v-loading="loading" class="padding-10 knowledge-box">
        <el-row :gutter="20" v-if="knowledgeList.length">
          <el-col
              v-for="(item, index) in knowledgeList"
              :key="index"
              :span="8"
          >
            <div
                class="flex justify-content-center item-kno border-radius margin-bottom-20 padding-15"
                style="position:relative; overflow: hidden"
                @click="useKnowledge(item)"
            >
              <div class="label" v-if="knowledgeStore.getKnowledge().id === item.id">
                <el-icon class="icon-success">
                  <component is="Check"></component>
                </el-icon>
              </div>
              <div class="w-50 text-center">
                <el-image
                    fit="cover"
                    :src="imagePrefix + item.avatar"
                    :preview-src-list="allAvatars"
                    :initial-index="index"
                    class="w-50 h-50"
                />
              </div>
              <div class="knowledge-info pointer">
                <div class="text-ellipsis title" :title="item.name">
                  <el-text class="font-size-2xl font-bold">{{ item.name }}</el-text>
                </div>
                <el-tooltip
                    effect="dark"
                >
                  <template #content>
                    <div style="max-width: 400px">{{ item.description }}</div>
                  </template>
                  <div class="description flex align-items-center">
                    <div class="desc-b">
                      <el-text>{{ item.description }}</el-text>
                    </div>
                  </div>
                </el-tooltip>
                <div class="view flex align-items-center" v-if="isPrivate === 0">
                  <el-icon style="color: var(--el-color-danger)"><FireFilled/></el-icon>
                  <span class="font-size-xs margin-left-5">{{item.select_number}}</span>
                  <el-tooltip
                    effect="dark"
                    content="文件下载次数"
                  >
                    <el-icon class="margin-left-30"><component is="Download"/></el-icon>
                  </el-tooltip>
                  <span class="font-size-xs margin-left-5">{{item.download_times}}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-empty description="暂无知识库" v-else/>
      </div>
    </div>
    <template #footer>
      <pagination
          :total="knowledgeTotal"
          v-model:page="query.page"
          v-model:limit="query.limit"
          @pagination="getList"
      />
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.item-kno {
  background: var(--el-bg-color);
  transition: color 0.2s, background-color 0.2s;
  box-shadow: 0 0 6px rgba(0, 0, 0, 0.24);
  position: relative;
}

.dark {
  .item-kno {
    background: var(--el-color-info-light-9);
    box-shadow: var(--el-box-shadow-lighter);
  }
}

.label {
  width: 46px;
  height: 26px;
  background-color: #13ce66;
  color: #FFFFFF;
  transform: rotate(45deg);
  text-align: center;
  position: absolute;
  right: -17px;
  top: -7px; 
  .icon-success {
    transform: rotate(-45deg);
    font-size: 24px;
    margin-left: 4px;
    margin-top: 4px;
  }
}
      
.knowledge-box {
  margin-top: 10px;
  overflow-y: auto;
  overflow-x: hidden;
  height: calc(100vh - 280px);
}
.knowledge-base {
  .knowledge-info {
    width: calc(100% - 50px);
    padding-left: 12px;

    .description {
      height: 50px;
      overflow: hidden;
      .desc-b {
        max-height: 48px;
        display: -webkit-box;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
    }

    .title {
      width: calc(100% - 30px);
    }
    .view {
      color: var(--el-color-info);
      position: relative;
      top: 5px;
    }
  }
}
</style>